package logic

import (
	"context"
	"fmt"
	"math/rand"
	"user-goods/models/cache"
	"user-goods/models/mysql"
	"user-goods/pkg"

	"user-goods/userrpc/internal/svc"
	"user-goods/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("mobile", in.Mobile).Find(&user)

	if user.ID == 0 {
		user = mysql.User{
			Mobile:    in.Mobile,
			Password:  pkg.Md5str(in.Password),
			HeadImage: "https://ts1.tc.mm.bing.net/th/id/OIP-C.rPQTtL06uTRQSkiUvIGykwAAAA?w=176&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.7&pid=3.1&rm=2",
			Name:      fmt.Sprintf("用户%d", rand.Intn(10000)),
		}
		mysql.DB.Debug().Create(&user)
	} else {
		if user.Password != pkg.Md5str(in.Password) {
			return nil, fmt.Errorf("密码错误")
		}
	}

	sum, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if sum != in.SendCode {
		return nil, fmt.Errorf("短信验证码错误")
	}

	result, _ := cache.Rdb.Get(l.ctx, "captCha"+in.Mobile).Result()
	if result != in.CaptCha {
		return nil, fmt.Errorf("图形验证码错误")
	}

	return &userrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
